let canvas = document.getElementById('canvas');
let ct = canvas.getContext('2d');
let width = canvas.width;
let height = canvas.height;
let drag = false;
let img = null,
    imgX = 0,
    imgY = 0,
    imgPrevX = 0, // 鼠标按下时图片的坐标
    imgPrevY = 0,
    imgWidth = 0,
    imgHeight = 0,
    imgMaxWidth = 0; // 图片最大放大尺寸
let downX = 0, // 鼠标按下时，鼠标的坐标
    downY = 0;
let zoom = 1; // 缩放倍数

canvas.addEventListener('mousedown', mousedown);
canvas.addEventListener('mousemove', mousemove);
document.addEventListener('mouseup', mouseup);
canvas.addEventListener('mousewheel', mousewheel);

img = new Image();
img.src = '正方形小.jpg';
img.onload = function () {
  if (this.width <= width && this.height <= height) {
    imgWidth = this.width;
    imgHeight = this.height;
    setXY(this.width, this.height);
  } else {
    if (this.width < this.height) {
      // 竖图
      imgHeight = height;
      imgWidth = this.width * height / this.height;
      setXY(imgWidth, '');
    } else if (this.width === this.height) {
      // 正方形图
      imgWidth = width;
      imgHeight = height;
    } else {
      // 横图
      imgWidth = width;
      imgHeight = this.height * width / this.width
      setXY('', imgHeight);
      console.log(this.height);
    }
  }
  
  imgMaxWidth = this.width * 4;
  drawImg();
}

function setXY(w, h) {
  imgX = w ? (width - w) / 2 : 0;
  imgY = h ? (height - h) / 2 : 0;
}

function mousedown(e) {
  downX = e.offsetX;
  downY = e.offsetY;
  imgPrevX = imgX;
  imgPrevY = imgY;
  drag = true;
}

function mousemove(e) {
  if (!drag) return;
  imgX = imgPrevX + e.offsetX - downX;
  imgY = imgPrevY + e.offsetY - downY;
  drawImg();
}

function mouseup(e) {
  drag = false;
}

function mousewheel(e) {
  let wd = e.wheelDelta > 0;

  if (wd && imgWidth >= imgMaxWidth) {
    return
  }

  zoom = zoom * wd ? 1.1 : 0.9;
  imgX = (imgX - e.offsetX) * zoom + e.offsetX
  imgY = (imgY - e.offsetY) * zoom + e.offsetY
  imgWidth = imgWidth * zoom;
  imgHeight = imgHeight * zoom;
  drawImg();
}

// 清除画布
function clear() {
  ct.clearRect(0, 0, width, height);
}

// 绘制图片
function drawImg() {
  clear();
  ct.drawImage(img, imgX, imgY, imgWidth, imgHeight);
}